import { getCurrentInstance, onUnmounted } from 'vue'
import axios, { type CancelTokenSource } from 'axios'
import { debounce } from 'lodash'
import type { RequestFn, RequestParams } from '../types'

export function useDataFetching<T>(requestFn: RequestFn, processResult: (data: T) => void) {
  let cancelTokenSource: CancelTokenSource | null = null

  const executeRequest = (params: RequestParams) => {
    console.log('发起请求', params)

    if (cancelTokenSource) {
      cancelTokenSource.cancel('取消上一次请求')
      cancelTokenSource = null
    }

    cancelTokenSource = axios.CancelToken.source()

    requestFn(params, {
      cancelToken: cancelTokenSource.token,
    }).then(({ resultBody: data }) => {
      processResult(data as T)
    })
  }

  const debouncedExecute = debounce(executeRequest, 800)

  if (getCurrentInstance()) {
    onUnmounted(() => {
      if (cancelTokenSource) {
        cancelTokenSource.cancel('组件卸载，取消请求')
        cancelTokenSource = null
      }
    })
  }

  return {
    executeRequest: debouncedExecute,
  }
}
